import { Request, Response } from 'express';
import { InfluxService } from '../services/InfluxService';
import { MqttService } from '../services/MqttService';
import { ApiResponse } from '../types';

export class DeviceController {
  private influxService: InfluxService;
  private mqttService: MqttService;

  constructor() {
    this.influxService = new InfluxService();
    this.mqttService = new MqttService();
  }

  // 获取设备列表
  async getDevices(req: Request, res: Response): Promise<void> {
    try {
      // 这里可以从InfluxDB查询所有设备
      const response: ApiResponse = {
        success: true,
        data: [],
        message: '设备列表获取成功',
      };
      
      res.json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : '获取设备列表失败',
      };
      res.status(500).json(response);
    }
  }

  // 获取设备最新数据
  async getDeviceData(req: Request, res: Response): Promise<void> {
    try {
      const { deviceId } = req.params;
      if (!deviceId) {
        const response: ApiResponse = {
          success: false,
          error: '设备ID不能为空',
        };
        res.status(400).json(response);
        return;
      }
      
      const { limit = '10' } = req.query;

      const data = await this.influxService.getLatestDeviceData(
        deviceId, 
        parseInt(limit as string, 10) || 10
      );

      const response: ApiResponse = {
        success: true,
        data,
        message: '设备数据获取成功',
      };
      
      res.json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : '获取设备数据失败',
      };
      res.status(500).json(response);
    }
  }

  // 获取设备统计信息
  async getDeviceStats(req: Request, res: Response): Promise<void> {
    try {
      const { deviceId } = req.params;
      if (!deviceId) {
        const response: ApiResponse = {
          success: false,
          error: '设备ID不能为空',
        };
        res.status(400).json(response);
        return;
      }
      
      const { timeRange = '-1h' } = req.query;

      const stats = await this.influxService.getDeviceStats(
        deviceId, 
        (timeRange as string) || '-1h'
      );

      const response: ApiResponse = {
        success: true,
        data: stats,
        message: '设备统计信息获取成功',
      };
      
      res.json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : '获取设备统计信息失败',
      };
      res.status(500).json(response);
    }
  }

  // 向设备发送指令
  async sendCommand(req: Request, res: Response): Promise<void> {
    try {
      const { deviceId } = req.params;
      if (!deviceId) {
        const response: ApiResponse = {
          success: false,
          error: '设备ID不能为空',
        };
        res.status(400).json(response);
        return;
      }
      
      const { command, data } = req.body;

      if (!command) {
        const response: ApiResponse = {
          success: false,
          error: '指令不能为空',
        };
        res.status(400).json(response);
        return;
      }

      const topic = `devices/${deviceId}/commands`;
      const message = JSON.stringify({ command, data, timestamp: Date.now() });

      await this.mqttService.publish(topic, message);

      const response: ApiResponse = {
        success: true,
        message: '指令发送成功',
      };
      
      res.json(response);
    } catch (error) {
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : '发送指令失败',
      };
      res.status(500).json(response);
    }
  }
}
